#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t " << proc << " serverip serverport\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int socketfd = ::socket(AF_INET, SOCK_STREAM, 0);

    if (socketfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }

    // tcp client 不要显示bind
    struct sockaddr_in serveraddr;

    memset(&serveraddr, 0, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(serverport);
    serveraddr.sin_addr.s_addr = inet_addr(serverip.c_str());

    // 连接的时候会bind
    int n = connect(socketfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
    if (n < 0)
    {
        std::cerr << "connect error" << std::endl;
        exit(3);
    }

    while (true)
    {
        std::cout << "Please Enter#";
        std::string outstring;
        std::getline(std::cin, outstring);

        // write 发消息
        ssize_t n = send(socketfd, outstring.c_str(), outstring.size(), 0);

        if (n > 0)
        {
            char inbuf[1024];
            //收消息
            ssize_t m = recv(socketfd, inbuf, sizeof(inbuf) - 1, 0);

            if (m > 0)
            {
                inbuf[m] = 0;
                std::cout << inbuf << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
     
   ::close(socketfd);

    return 0;
}
